<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="1000px" :modal-append-to-body="false" center>
    <!-- :modal-append-to-body = "false" 处理遮罩层在模态框上的bug -->
    <div class="main">
      <el-form ref="combatReportFrom" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="作战总结" prop="title" class="el-form-item-first">
          <el-input class="elInputText" v-model="form.title" :disabled="echo.title" />
          <el-button v-if="isEdit && echo.title" icon="el-icon-edit" class="cancel"
            @click="inputBoxEdit('title', form.title)">编辑
          </el-button>
          <el-button v-if="isEdit && !echo.title" icon="el-icon-delete" class="cancel"
            @click="inputBoxEditCancel('title')">取消
          </el-button>
        </el-form-item>
        <el-form-item label="作战描述" prop="desc">
          <div class="btn" v-if="isEdit">
            <el-button v-if="echo.desc" class="cancel" icon="el-icon-edit" @click="inputBoxEdit('desc', form.desc)">编辑
            </el-button>
            <el-button v-if="!echo.desc" class="cancel" icon="el-icon-delete" @click="inputBoxEditCancel('desc')">取消
            </el-button>
          </div>
          <el-input class="elTextarea" type="textarea" v-model="form.desc" :autosize="{ minRows: 7, maxRows: 15 }"
            :disabled="echo.desc" />
        </el-form-item>
        <el-form-item label="作战结果" prop="files">
          <!-- auto-upload	是否在选取文件后立即进行上传 默认是true-->
          <div class="btn" v-if="isEdit">
            <el-button v-if="echo.file" class="cancel" icon="el-icon-edit" @click="inputBoxEdit('file', fileList)">编辑
            </el-button>
            <el-button v-if="!echo.file" class="cancel" icon="el-icon-delete" @click="inputBoxEditCancel('file')">取消
            </el-button>
          </div>
          <el-upload ref="upload" action="#" :on-change="handleChange" :accept="acceptType" list-type="picture-card"
            :disabled="echo.file" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :auto-upload="false"
            :file-list="fileList" :headers="{'Content-Type': 'multipart/form-data',}">
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog title="图片预览" width="800px" :visible.sync="lookDialogVisible" append-to-body center>
            <img width="100%" :src="dialogImageUrl" alt="" />
            <div class="btn_groups">
              <div class="cancel" @click="lookDialogVisible = false">
                <img src="@/assets/image/index/icon_cha.png" />
                <span>取消</span>
              </div>
            </div>
          </el-dialog>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn_groups">
      <div class="cancel" @click="cancel()">
        <img src="@/assets/image/index/icon_cha.png" />
        <span>取消</span>
      </div>
      <div class="success" @click="success()">
        <img src="@/assets/image/index/icon_gou.png" />
        <span>确定</span>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  postAddBattleReport,
  getReadBattleReport,
  putUpdate_battle_report,
} from "@/api/execute";
export default {
  name: "OperationalReportDialog",
  data() {
    return {
      acceptType: '.png,.jpg,.JPG,.JPG',
      ImageFormat: ['png', 'jpg'],
      dialogVisible: false,
      accept: [],
      isAdd: true,
      echo: {
        title: false,
        desc: false,
        file: false,
      },
      isEdit: false,
      form: {
        title: "",
        desc: "",
        report_type: "war",
        files: [],
        parent_id: "22",
      },
      oldForm: {},
      oldFileList: [],
      fileList: [],
      rules: {
        title: [{ required: true, message: "请输入作战总结", trigger: "blur" }],
        desc: [{ required: true, message: "请输入作战描述", trigger: "blur" }],
      },
      value1: "",
      search: {
        name: "",
        picker: "",
      },
      dialogImageUrl: "",
      lookDialogVisible: false,
      disabled: false,
      backFileList: [],
    };
  },
  computed: {
    title() {
      return this.isAdd
        ? "添加作战报告"
        : !this.echo.title || !this.echo.desc || !this.echo.file
          ? "编辑作战报告"
          : "作战报告";
    },
  },
  methods: {
    //编辑
    inputBoxEdit(item, form) {
      this.echo[item] = false;
      if (item == "file") {
        this.oldFileList = form;
      } else {
        this.oldForm[item] = form;
      }
    },
     //取消
    inputBoxEditCancel(item) {
      this.echo[item] = true;
      if (item == "file") {
        // this.$set(this.form, item, this.$refs.upload.fileList)
        // this.form[item] = this.$refs.upload.fileList
        // this.fileList = this.$refs.upload.fileList
        // this.backFileList = this.$refs.upload.fileList
        this.oldForm = this.$refs.upload.fileList
        console.log('33',this.oldForm,this.fileList, this.form, this.form[item],this.$refs.upload.fileList);
      } else {
        this.form[item] = this.oldForm[item];
      }
    },
    inputBoxConserve(item, form) {
      this.echo[item] = true;
      if (item == "file") {
        this.form[item] = form;
        this.oldFileList = form;
      } else {
        this.form[item] = form;
      }
    }, 
    init() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.isAdd = true;
    },
    cancel() {
      this.$refs.combatReportFrom.resetFields();
      this.dialogVisible = false;
      this.form = {
        title: "",
        desc: "",
        report_type: "war",
        files: [],
      };
      this.fileList = [];
      this.backFileList = [];
      this.echo = {
        title: false,
        desc: false,
        file: false,
      };
    },
    success() {
      this.$refs.combatReportFrom.validate(async (valid) => {
        if (valid) {
          if (this.isAdd) {
            if (this.form.files.length == 0) return this.$message.error("请上传作战结果");
          } else {
            if (this.backFileList.length == 0) return this.$message.error("请上传作战结果");
          }
          let formData = new FormData();
          formData.append("title", this.form.title);
          formData.append("desc", this.form.desc);
          formData.append("report_type", this.form.report_type);
          if (this.isAdd) {
            formData.append("parent_id", this.form.parent_id);
            for (let i = 0; i < this.form.files.length; i++) {
              if (this.form.files[i].raw) {
                formData.append("files", this.form.files[i].raw);
              }
            }
            let [res,err] = await postAddBattleReport(formData);
            if (err) return this.$message.error("添加失败");
            if (res?.code == 201) {
              this.cancel();
            }
          } else {
            formData.append("report_id", this.form.report_id);
            for (let i = 0; i < this.backFileList.length; i++) {
              if (this.backFileList[i].raw) {
                formData.append("files", this.backFileList[i].raw);
              }
            }
            let [res,err] = await putUpdate_battle_report(formData);
            if (err) return this.$message.error("添加失败");
            if (res?.code == 200) {
              this.cancel();
            }
          }
        } else {
          console.log("添加失败");
          return false;
        }
      });
    },
    // 删除
    handleRemove(file) {
      if (!this.isAdd) {
        let removeData = this.backFileList.findIndex((item) => {
          if (item.raw.name == file.name) {
            return true
          }
        })
        this.backFileList.splice(removeData, 1);
      }
    },
    //点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.lookDialogVisible = true;
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList) {
      let fileTypeResults = this.ImageFormat.some((item) => item == file.name.split(".")[1])
      if (!fileTypeResults) {
        let fileListResult = fileList.indexOf((item) => {
          if (item.raw.name == file.name) {
            return true
          }
        })
        fileList.splice(fileListResult, 1);
        return this.$message.error(`请上传${this.acceptType}类型的文件`)
      } else {
        if (this.isAdd) {
          this.form.files = fileList;
        } else {
          this.backFileList.push({ raw: file.raw, url: file.url });
        }
      }
      console.log('handleChange',this.$refs.upload.fileList,'file',file,'fileList',fileList);
    },
    imageUrlToBase64(imageUrl, filename, fileTyp) {
      let image = new Image(); // 一定要设置为let，不然图片不显示
      image.setAttribute("crossOrigin", "anonymous"); // 解决跨域问题
      image.src = imageUrl;
      image.onload = () => {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var quality = 0.8;
        var dataURL = canvas.toDataURL(`image/${fileTyp}`, quality); // 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
        this.base64toFile(dataURL, filename);
      };
    },
    base64toFile(dataurl, filename) {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let suffix = mime.split("/")[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      let file = new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
      this.backFileList.push({ raw: file, url: URL.createObjectURL(file) });
    },
    async editReport() {
      this.fileList = [];
      let [res] = await getReadBattleReport('270edce8-38c4-11ed-91d0-fd4b37971774');
      console.log(res, "editReport1");
      if (res?.code == 200) {
        let { desc, title, report_type, file_address, report_id } = res.msg;
        for (let i = 0; i < file_address.length; i++) {
          file_address[i] = {
            name: file_address[i].split("/")[2].split(".")[0],
            type: file_address[i].split("/")[2].split(".")[1],
            url: this.$imgUrl + file_address[i],
          };
        }
        for (let j = 0; j < file_address.length; j++) {
          console.log('file_address[j].type', file_address[j].type);
          this.imageUrlToBase64(file_address[j].url, file_address[j].name, file_address[j].type);
        }
        this.form = {
          title,
          desc,
          report_type,
          files: [],
          report_id,
        };
        this.fileList = file_address;
      }
      console.log(this.form);
      this.isEdit = true;
      this.echo = {
        title: true,
        desc: true,
        file: true,
      };
      this.isAdd = false;
      this.dialogVisible = true;
    },
  },
};
</script>
<style lang="less" scoped>
@import url("~@/assets/less/pop_up_style.less");

.cancel {
  background-color: rgb(0, 117, 169);
  color: #fff;
  border: none;
  border-radius: 10px;
}

.el-form-item-first :deep(.el-form-item__content) {
  display: flex;
}

.el-form-item .btn {
  float: right;
}

.success {
  background-color: rgb(235, 97, 0);
  color: #fff;
  border: none;
  border-radius: 5px;
}

.elInputText {
  margin-right: 5px;
}

.elTextarea {
  margin-top: 10px;
}

// form表单样式
:deep(.el-form-item__label) {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 18px;
  color: #fff;
  line-height: 40px;
  padding: 0 12px 0 0;
  box-sizing: border-box;
}

// el-input样式
:deep(.el-input__inner) {
  -webkit-appearance: none;
  background-color: rgba(9, 25, 58, 0.43);
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  box-sizing: border-box;
  color: #fff;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: 0;
  padding: 0 15px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100%;
}

.btn_groups {
  color: #fff;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;

  div {
    width: 120px;
    height: 45px;
    line-height: 45px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
  }

  .cancel {
    margin-right: 20px;
    background-color: rgb(0, 117, 169);

    img {
      margin-right: 10px;
      width: 22px;
      height: 22px;
    }
  }

  .success {
    background-color: rgb(235, 97, 0);

    img {
      margin-right: 10px;
      width: 28px;
      height: 18px;
    }
  }
}

:deep(.el-upload--picture-card) {
  background: rgba(9, 25, 58, 0.43);

  &:hover {
    border-color: #dcdfe6;
    color: #dcdfe6;
  }
}

:deep(.el-upload:focus) {
  border-color: #dcdfe6;
  color: #dcdfe6;
}

// 作战描述 el-textarea样式
:deep(.el-textarea__inner) {
  background: rgba(9, 25, 58, 0.43);
  color: #fff;

  &:focus {
    border-color: #dcdfe6;
  }
}
</style>
<style>
.el-input.is-disabled .el-input__inner,
.el-textarea.is-disabled .el-textarea__inner {
  background-color: rgba(0, 117, 169, 0.2) !important;
  border-color: rgba(0, 117, 169, 0.7) !important;
  color: #fff !important;
}
</style>